package com.knife.bbs.action;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpSession;

import com.knife.util.CommUtil;
import com.knife.util.MD5;
import com.knife.util.TagUtil;
import com.knife.web.ActionContext;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.web.tools.AbstractCmdAction;
import com.knife.web.tools.IPageList;
import com.knife.bbs.business.*;
import com.knife.bbs.object.UserInfo;
import com.knife.bbs.domain.WebMessage;

/**
 * <p>
 * Title:BBS用户处理Action
 * </p>
 * <p>
 * Description: 处理BBS用户对象相关操作的Action,包括用户注册、用户增加、用户设置、用户修改、用户删除等! <br>
 * 通过继承com.knife.web.tools.AbstractCmdAction,实现简单的命令式Action处理,去除了复杂烦锁的if else语句
 * </p>
 */
public class BBSUserAction extends BBSAction {
	private BBSUserService userService = new BBSUserService();

	public Page doInit(WebForm form, Module module) {
		// TODO Auto-generated method stub
		return module.findPage("/" + skin + "/", "login");
	}

	/**
	 * 查询所有用户
	 * 
	 * @param form
	 * @param module
	 * @return 用户列表Page
	 */
	public Page doList(WebForm form, Module module) {
		com.knife.bbs.domain.UserInfo auser = new com.knife.bbs.domain.UserInfo();
		UserInfo u = new UserInfo(auser);
		if (!BBSRights.checkRights(u, "list", getCurrentUser()))
			return new Page("popedomError", "norights.htm", "html", "/" + skin
					+ "/");
		return doQuery(form, module);
	}

	/**
	 * 设置个人用户信息
	 * 
	 * @param form
	 * @param module
	 * @return 返回编辑用户Page
	 */
	public Page doSetting(WebForm form, Module module) {
		ActiveUser user = getCurrentUser();
		if (user == null) {
			form.addResult("msg", "请先登录！");
			return module.findPage("/" + skin + "/", "login");
		}
		return doEdit(form, module);
	}

	public Page doNew(WebForm form, Module module) {
		return module.findPage("/" + skin + "/", "edit");
	}

	/**
	 * 注销用户,清除session,并跳转到相应的页面
	 * 
	 * @param form
	 * @param module
	 * @return
	 */
	public Page doLogout(WebForm form, Module module) {
		// activeUserService.remove(this.getCurrentUser());
		ActionContext.getContext().getSession().removeAttribute("bbsuser");
		form.addResult("url", "");
		return new Page("clientforward", "forward.htm", "html", "/" + skin
				+ "/");
	}

	/**
	 * 用户登录验证,通过客户端用户的登录信息验证用户输入
	 * 
	 * @param form
	 * @param module
	 * @return 根据用户输入的情况返回相应的Page
	 */
	public Page doLogin(WebForm form, Module module) {
		ActionContext.getContext().getSession().removeAttribute("bbsuser");
		Page page = null;
		ActiveUser user = null;
		// 1.SSO单点登录
		String sso_username = ActionContext.getContext().getRequest()
				.getRemoteUser();
		if (sso_username != null) {
			user = userService.login(
					CommUtil.null2String(form.get("username")),
					MD5.encode(CommUtil.null2String(form.get("password"))),
					CommUtil.null2String(form.get("cktime")), ActionContext
							.getContext().getRequest().getRemoteAddr());
		}
		// 2.正常登录
		if (user == null) {
			String randomCode = (String) ActionContext.getContext()
					.getSession().getAttribute("rand");
			String rcode = CommUtil.null2String(form.get("randomCode"));
			if (rcode.length() == 0 || !rcode.equals(randomCode)) {
				form.addResult("msg", "验证码不正确，请重新输入！");
				return module.findPage("/" + skin + "/", "login");
			}
			user = userService.login(
					CommUtil.null2String(form.get("username")),
					MD5.encode(CommUtil.null2String(form.get("password"))),
					CommUtil.null2String(form.get("cktime")), ActionContext
							.getContext().getRequest().getRemoteAddr());
		}
		if (user != null) {
			ActionContext.getContext().getSession()
					.setAttribute("bbsuser", user);// 登录标志
			// page = module.findPage("loginSuccess");
			form.addResult("js", "top.location.href('');");
			page = new Page("index", "/manage/javascript.html", "html");
		} else {
			form.addResult("msg", "用户名或者密码不正确，请重新输入！");
			page = module.findPage("/" + skin + "/", "login");
		}
		return page;
	}

	/**
	 * 用户注册
	 * 
	 * @param form
	 * @param module
	 * @return 直接跳转到用户注册Page
	 */
	public Page doReg(WebForm form, Module module) {
		return module.findPage("/" + skin + "/", "reg");
	}

	public Page doShowChangePass(WebForm form, Module module) {
		ActiveUser user = getCurrentUser();
		if (user == null) {
			form.addResult("msg", "请先登录！");
			return module.findPage("/" + skin + "/", "login");
		}
		return module.findPage("/" + skin + "/", "changePass");
	}

	/**
	 * 修改用户信息
	 * 
	 * @param form
	 * @param module
	 * @return 添加成功,若当前用户为系统管理员,则返回列表Page,否则返回个人信息设置Page,失败则返回编辑Page.
	 */
	public Page doChangePass(WebForm form, Module module) {
		String cid = CommUtil.null2String(form.get("cid"));
		ActiveUser user = getCurrentUser();
		UserInfo obj = null;
		if (!cid.equals("")) {
			obj = userService.getUserInfo(cid);
		} else if (user != null) {
			obj = userService.getUserInfoByName(user.getUsername());
		}
		if (obj != null) {
			// 在Action中检测权限
			if (!BBSRights.checkRights(obj, "update", user))
				return new Page("popedomError", "norights.htm", "html", "/"
						+ skin + "/");
			String password = CommUtil.null2String(form.get("password"));
			String oldPassword = CommUtil.null2String(form.get("oldPassword"));
			if (obj.getPassword().equals(MD5.encode(oldPassword))) {
				obj.setPassword(MD5.encode(password));
				userService.update(obj);
				form.addResult("msg", "密码修改成功！");
			} else {
				form.addResult("msg", "旧密码输入不正确！");
			}
		} else {
			form.addResult("msg", "你所修改的用户不存在！");
		}

		return module.findPage("/" + skin + "/", "changePass");
	}

	public Page doControl(WebForm form, Module module) {
		ActiveUser user = getCurrentUser();
		if (user == null) {
			form.addResult("msg", "请先登录！");
			return module.findPage("login");
		}
		UserInfo obj = null;
		obj = userService.getUserInfoByName(user.getUsername());
		System.out.println("-----获取到的用户名是:" + user.getUsername());
		if (obj != null) {
			form.addResult("user", obj);
			form.addResult("messageNum", userService.getUserMessageNum(obj));
			form.addResult("replyMessageNum", userService.getUserReplyNum(obj));// obj.replyNum());
			form.addResult("eliteMessageNum",
					userService.getUserEliteMessageNum(obj));
		}
		return module.findPage("control");
	}

	/**
	 * 用户注册码->保存用户注册信息
	 * 
	 * @param form
	 * @param module
	 * @return 注册成功则返回登录Page,失败则返回注册Page
	 */
	public Page doRegSave(WebForm form, Module module) {
		String username = CommUtil.null2String(form.get("username"));
		String password = CommUtil.null2String(form.get("password"));
		String password1 = CommUtil.null2String(form.get("password1"));
		if (username.equals("") || password.equals("")) {
			form.addResult("msg", "用户名及密码不能为空！");
			return module.findPage("/" + skin + "/", "reg");
		}
		if (!password.equals(password1)) {
			form.addResult("msg", "两次输入的密码不相同！");
			return module.findPage("/" + skin + "/", "reg");
		}
		com.knife.bbs.domain.UserInfo userInfo = new com.knife.bbs.domain.UserInfo();
		userInfo.setUsername(username);
		userInfo.setPassword(MD5.encode(password));
		userInfo.setEmail(CommUtil.null2String(form.get("email")));
		userInfo.setSex(CommUtil.null2String(form.get("sex")));
		userInfo.setTel(CommUtil.null2String(form.get("tel")));
		userInfo.setQq(CommUtil.null2String(form.get("qq")));
		userInfo.setIntro(CommUtil.null2String(form.get("intro")));
		userInfo.setInputtime(new Date());
		userInfo.setStatus(new Integer(0));
		if (userService.getUserInfoByName(username) != null) {
			form.addResult("msg", "用户名已经存在！");
			return module.findPage("/" + skin + "/", "reg");
		}
		if (userService.add(userInfo)) {
			form.addResult("msg", "用户注册成功！");
			ActiveUser user = userService.login(username, MD5.encode(password),
					"0", ActionContext.getContext().getRequest()
							.getRemoteAddr());
			MessageUtil.sendSystemMessage(WebMessage.WELCOMEMSG,
					userInfo.getUsername());
			if (user != null) {
				ActionContext.getContext().getSession()
						.setAttribute("bbsuser", user);// 登录标志
				// return module.findPage("loginSuccess");
				form.addResult("js", "top.location.href('');");
				return new Page("index", "/manage/javascript.html", "html");
			}
		} else {
			form.addResult("msg", "用户注册失败！");
			return module.findPage("/" + skin + "/", "reg");
		}
		return module.findPage("/" + skin + "/", "reg");
	}

	/**
	 * 添加用户信息->系统管理员使用
	 * 
	 * @param form
	 * @param module
	 * @return 添加成功则返回列表Page,失败则返回编辑Page
	 */
	public Page doAdd(WebForm form, Module module) {
		String userName = CommUtil.null2String(form.get("username"));
		com.knife.bbs.domain.UserInfo userInfo = new com.knife.bbs.domain.UserInfo();
		userInfo.setUsername(userName);
		userInfo.setPassword(MD5.encode(CommUtil.null2String(form
				.get("password"))));
		userInfo.setEmail(CommUtil.null2String(form.get("email")));
		userInfo.setSex(CommUtil.null2String(form.get("sex")));
		userInfo.setTel(CommUtil.null2String(form.get("tel")));
		userInfo.setQq(CommUtil.null2String(form.get("qq")));
		userInfo.setIntro(CommUtil.null2String(form.get("intro")));
		userInfo.setPhoto(CommUtil.null2String(form.get("photo")));
		userInfo.setStatus(new Integer(0));
		if (userService.getUserInfoByName(userName) != null) {
			form.addResult("msg", "用户名已经存在！");
			return module.findPage("/" + skin + "/", "edit");
		}
		if (userService.add(userInfo)) {
			form.addResult("msg", "用户添加成功！");
		} else {
			form.addResult("msg", "用户添加失败！");
			return module.findPage("/" + skin + "/", "edit");
		}
		return doQuery(form, module);
	}

	/**
	 * 修改用户信息
	 * 
	 * @param form
	 * @param module
	 * @return 添加成功,若当前用户为系统管理员,则返回列表Page,否则返回个人信息设置Page,失败则返回编辑Page.
	 */
	public Page doUpdate(WebForm form, Module module) {
		String cid = CommUtil.null2String(form.get("cid"));
		ActiveUser user = getCurrentUser();
		UserInfo obj = null;
		if (!cid.equals("")) {
			obj = userService.getUserInfo(cid);
		} else if (user != null) {
			obj = userService.getUserInfoByName(user.getUsername());
		}
		if (obj != null) {
			// 在Action中检测权限
			if (!BBSRights.checkRights(obj, "update", user))
				return new Page("popedomError", "norights.htm", "html", "/"
						+ skin + "/");
			obj.setPassword(MD5.encode(CommUtil.null2String(form
					.get("password"))));
			obj.setEmail(CommUtil.null2String(form.get("email")));
			obj.setSex(CommUtil.null2String(form.get("sex")));
			obj.setTel(CommUtil.null2String(form.get("tel")));
			obj.setQq(CommUtil.null2String(form.get("qq")));
			obj.setIntro(CommUtil.null2String(form.get("intro")));
			obj.setPhoto(CommUtil.null2String(form.get("photo")));
			userService.update(obj);
		} else {
			form.addResult("msg", "你所修改的用户不存在！");
		}
		if (!BBSRights.checkRights(obj, "isAdministrator", user)) {
			return module.findPage("/" + skin + "/", "setting");
		}
		return doQuery(form, module);
	}

	/**
	 * 删除用户
	 * 
	 * @param form
	 * @param module
	 * @return 返回列表Page
	 */
	public Page doDel(WebForm form, Module module) {
		String cid = CommUtil.null2String(form.get("cid"));
		ActiveUser user = getCurrentUser();
		UserInfo obj = userService.getUserInfo(cid);
		if (obj != null) {
			if (!BBSRights.checkRights(obj, "del", user)) {
				return new Page("popedomError", "norights.htm", "html", "/"
						+ skin + "/");
			}
			userService.del(obj);
			form.addResult("msg", "删除成功！");
		}
		return doQuery(form, module);
	}

	/**
	 * 编辑用户信息-从持久层读取数据显示到View中
	 * 
	 * @param form
	 * @param module
	 * @return 返回编辑Page
	 */
	public Page doEdit(WebForm form, Module module) {
		String cid = CommUtil.null2String(form.get("cid"));
		ActiveUser user = getCurrentUser();
		UserInfo obj = null;
		if (!cid.equals("")) {
			obj = userService.getUserInfo(cid);
		} else if (user != null) {
			obj = userService.getUserInfoByName(user.getUsername());
		}
		if (!BBSRights.checkRights(obj, "edit", user))
			return new Page("popedomError", "norights.htm", "html", "/" + skin
					+ "/");
		if (obj != null)
			form.addPo(obj);
		return module.findPage("/" + skin + "/", "setting");
	}

	/**
	 * 显示用户信息
	 * 
	 * @param form
	 * @param module
	 * @return 返回用户信息显示Page
	 */
	public Page doShow(WebForm form, Module module) throws Exception {
		UserInfo obj = null;
		String userName = URLDecoder.decode(
				URLEncoder.encode((String) form.get("user"), "ISO8859_1"),
				"utf-8");
		;// CommUtil.toChinese(CommUtil.null2String(form.get("user")),ActionContext.getContext().getRequest().getCharacterEncoding());
		if (!userName.equals("")) {
			obj = userService.getUserInfoByName(userName);
		}
		if (obj != null) {
			form.addResult("obj", obj);
			form.addResult("messageNum", userService.getUserMessageNum(obj));
			form.addResult("replyMessageNum", userService.getUserReplyNum(obj));
			form.addResult("eliteMessageNum",
					userService.getUserEliteMessageNum(obj));
		}
		return module.findPage("/" + skin + "/", "show");
	}

	/**
	 * 查询用户信息
	 * 
	 * @param form
	 * @param module
	 * @return 返回用户列表
	 */
	public Page doQuery(WebForm form, Module module) {
		com.knife.bbs.domain.UserInfo auser = new com.knife.bbs.domain.UserInfo();
		UserInfo u = new UserInfo(auser);
		if (!BBSRights.checkRights(u, "list", getCurrentUser()))
			return new Page("popedomError", "norights.htm", "html", "/" + skin
					+ "/");
		int currentPage = CommUtil.null2Int(form.get("page"));
		int pageSize = CommUtil.null2Int(form.get("pageSize"));
		if (currentPage < 1)
			currentPage = 1;
		if (pageSize < 1)
			pageSize = 15;
		IPageList pList = userService.queryUser("1=1", pageSize, currentPage);
		if (pList != null) {
			com.knife.util.CommUtil.saveIPageList2WebForm(pList, form);
		}
		return module.findPage("/" + skin + "/", "list");
	}

	public Page doQueryByName(WebForm form, Module module) {
		com.knife.bbs.domain.UserInfo auser = new com.knife.bbs.domain.UserInfo();
		UserInfo u = new UserInfo(auser);
		if (!BBSRights.checkRights(u, "list", getCurrentUser()))
			return new Page("popedomError", "norights.htm", "html", "/" + skin
					+ "/");
		int currentPage = CommUtil.null2Int(form.get("page"));
		int pageSize = CommUtil.null2Int(form.get("pageSize"));
		if (currentPage < 1)
			currentPage = 1;
		if (pageSize < 1)
			pageSize = 15;
		String name = CommUtil.null2String(form.get("name"));
		IPageList pList = userService.queryUser("1=1 and userName='" + name
				+ "'", pageSize, currentPage);
		if (pList != null) {
			form.addResult("list", pList.getResult());
			form.addResult("pages", new Integer(pList.getPages()));
			form.addResult("rows", new Integer(pList.getRowCount()));
			form.addResult("page", new Integer(pList.getCurrentPage()));
			form.addResult(
					"gotoPageHTML",
					TagUtil.showPageHtml(pList.getCurrentPage(),
							pList.getPages()));
		}
		return module.findPage("/" + skin + "/", "list");
	}

	/**
	 * 查询在线用户
	 * 
	 * @param form
	 * @param module
	 * @return 返回在线用户列表Page
	 */
	public Page doOnline(WebForm form, Module module) {
		form.addResult("ip", ActionContext.getContext().getRequest()
				.getRemoteAddr());
		String userAgent = ActionContext.getContext().getRequest()
				.getHeader("User-Agent");
		String browser = userAgent.split(";")[1].trim();
		String os = userAgent.split(";")[2].trim();
		form.addResult("os", os);
		form.addResult("browser", browser);
		form.addResult("admin", ActiveUserService.getAdminNum());
		form.addResult("manager", ActiveUserService.getManagerNum());
		form.addResult("usernum", ActiveUserService.getUsersNum());
		form.addResult("guest", ActiveUserService.getGuestNum());
		form.addResult("total", ActiveUserService.getAllUserNum());
		int others = ActiveUserService.getAllUserNum()
				- ActiveUserService.getUsersNum();
		form.addResult("others", others);
		form.addResult("users", ActiveUserService.getAllUser());
		return module.findPage("/" + skin + "/", "onlineList");
	}

	/**
	 * 激活论坛帐号
	 * 
	 * @param form
	 * @param module
	 * @return 返回用户编辑页面
	 */
	public Page doActiveBBSUser(WebForm form, Module module) {
		String loginUser = "";
		HttpSession olSession = ActionContext.getContext().getSession();
		if (olSession != null) {
			if (olSession.getAttribute("loginuser") != null) {
				loginUser = olSession.getAttribute("loginuser").toString();
			}
		}
		if (loginUser.length() > 0) {
			UserInfo auser = userService.getUserInfoByName(loginUser);
			if (auser == null) {
				return module.findPage("/" + skin + "/", "active");
			} else {
				olSession.setAttribute("bbsuser", auser);
			}
		}
		return doEdit(form, module);
	}

	private ActiveUser getCurrentUser() {
		ActiveUser user = (ActiveUser) ActionContext.getContext().getSession()
				.getAttribute("bbsuser");
		return user;
	}
}
